#!/bin/sh

SP_MIN_MEM=512m
SP_MAX_MEM=1024m

SCRIPT="$0"
# SCRIPT may be an arbitrarily deep series of symlinks. Loop until we have the concrete path.
while [ -h "$SCRIPT" ] ; do
  ls=`ls -ld "$SCRIPT"`
  # Drop everything prior to ->
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    SCRIPT="$link"
  else
    SCRIPT=`dirname "$SCRIPT"`/"$link"
  fi
done
SERVER_HOME=`dirname "$SCRIPT"`/..
SERVER_HOME=`cd "$SERVER_HOME"; pwd`

SP_CLASSPATH=$CLASSPATH:$SERVER_HOME/config/:$SERVER_HOME/lib/*
MAIN_CLASS=com.lcxw.hxzbadmin.HxzbAdminApp
LOG_FILE_NAME=$SERVER_HOME/logs/HxzbAdminApp.log


#java opts config
SP_OPTS="-Dsp.home=$SERVER_HOME"
SP_OPTS="$SP_OPTS -Dlog4j.configuration=file:$SERVER_HOME/config/log4j2.xml"
SP_OPTS="$SP_OPTS -Xms${SP_MIN_MEM} -Xmx${SP_MAX_MEM}"
#SP_OPTS="$SP_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=8999"

if [ ! -d $SERVER_HOME/logs ]
then
    mkdir -p $SERVER_HOME/logs
fi

COMMAND=$1

start(){
    echo "starting ..."
    pid=`jps -l | grep $MAIN_CLASS|grep -v kill|awk '{print $1}'`
    if [ ${pid} ]; then
        echo "$MAIN_CLASS is already running on [$pid] "
    else
        nohup java $SP_OPTS -cp $SP_CLASSPATH $MAIN_CLASS >/dev/null 2>&1 &
        #java $SP_OPTS -cp $SP_CLASSPATH $MAIN_CLASS --spring.config.location=$CONF_FILE_NAME
        echo "please see the log --> '$LOG_FILE_NAME' or 'ps -ef|grep $MAIN_CLASS'"
        echo "Server has started! "
    fi
}

stop(){
    echo "stop ..."
    pid=`jps -l | grep $MAIN_CLASS|grep -v kill|awk '{print $1}'`
    echo "$MAIN_CLASS process's pid is $pid"

    if [ ${pid} ]; then
        kill -15 $pid
        echo "$MAIN_CLASS [$pid] is stoped!"
    fi

    sleep 5
    pid=`jps -l | grep $MAIN_CLASS|grep -v kill|awk '{print $1}'`
    if [ ${pid} ]; then
        kill -9 $pid
        echo "$MAIN_CLASS [$pid] is stoped!"
    else
        echo "Stop Server Success!"
    fi
}

status(){
     pid=`jps -l | grep $MAIN_CLASS|grep -v kill|awk '{print $1}'`
     if [ ${pid} ]
         then
            echo "$MAIN_CLASS is running: [$pid]"
         else
            echo "$MAIN_CLASS is NOT running"
     fi
}

log(){
    tail -f $LOG_FILE_NAME
}

docommand() {
    case "$COMMAND" in
        'start')
            start
            ;;

        'stop')
            stop
            ;;

        'restart')
            stop;
            start;
            ;;

        'status')
            status
            ;;
        'log')
            log
            ;;
		*)
		 	echo "usage: [start|stop|restart|status|log]"
			;;
    esac
}
docommand "$@"
exit 0